package com.wushi.lenovo.asia5b.app_ui.other.dialog;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mvp.base.BaseDialog;
import com.mvp.utils.DisplayUtils;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_model.voucher.VoucherModel;

import butterknife.BindView;

/**
 * Created by zhangyuncai on 2019/1/8.
 */
public class VoucherDetailDialog extends BaseDialog {
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_voucher_title)
    TextView tv_voucher_title;
    @BindView(R.id.iv_cancelsure_ok)
    ImageView iv_cancelsure_ok;
    @BindView(R.id.webview_layout)
    LinearLayout webviewLayout;
    private final VoucherModel voucherModel;
    protected WebView webView;

    public VoucherDetailDialog(Context context, VoucherModel voucherModel) {
        super(context);
        this.voucherModel = voucherModel;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_voucherdetail;
    }

    @Override
    protected void initView() {
//        tv_content.setMovementMethod(ScrollingMovementMethod.getInstance());
//
////        tv_content.setText(voucherModel.getTerms_and_condition());
//        String h5 = "<p style=\\\"font-weight: 400; text-align: center;\\\"><strong>TESTING</strong></p>\\r\\n<p style=\\\"font-weight: 400; text-align: center;\\\"><strong><img title=\\\"HNY2019.jpg\\\" src=\\\"https://res.cloudinary.com/dqfyvwfdj/image/upload/v1546409262/campaign/dd9fjxtdyxggmvmpcjyv.jpg\\\" alt=\\\"\\\" width=\\\"500\\\" height=\\\"500\\\" /></strong></p>\\r\\n<p style=\\\"font-weight: 400;\\\"><strong>TERMS AND CONDITIONS</strong></p>\\r\\n<p style=\\\"font-weight: 400;\\\">&nbsp;</p>\\r\\n<ol style=\\\"font-weight: 400;\\\">\\r\\n<li>The voucher may be used to book an AirAsiaGo Rate hotel with bookings made online at&nbsp;<a href=\\\"http://www.airasiago.com.my/?mdpcid=aagmy.direct.uob.termsconditions\\\">http://www.airasiago.com.my</a>. The voucher cannot be redeemed against car only bookings, flight only bookings, package only bookings or hotel only bookings of the hotels listed here:&nbsp;<a href=\\\"http://www.airasiago.com.my/p/corporate/coupon-exclude-hotels\\\">http://www.airasiago.com.my/p/corporate/coupon-exclude-hotels</a></li>\\r\\n<li>The voucher entitles you to 10% off the price of the travel reservation before the application of any taxes, applicable fees or additional costs.</li>\\r\\n<li>Voucher can only be redeemed if you pay online when booking is made at&nbsp;<a href=\\\"http://www.airasiago.com.my/?mdpcid=aagmy.direct.uob.termsconditions\\\">http://www.airasiago.com.my</a>&nbsp;and not applicable if you choose to pay at the hotel later.</li>\\r\\n<li>The voucher may not be used with other discount vouchers.</li>\\r\\n<li>In a multiple-room booking, the discount will only be applied to one room.</li>\\r\\n<li>The voucher cannot be redeemed against taxes, supplier fees, cancellation or change penalties, administrative fees or other miscellaneous charges, which are the sole responsibility of the customer.</li>\\r\\n<li>The voucher cannot be used for any booking previously made and will be deemed fully redeemed once a qualifying booking has been made.</li>\\r\\n<li>The voucher has no cash value and no refunds or cash alternative will be offered. Improper use of the voucher by you including but not limited to publication or selling of the voucher is prohibited and may constitute fraud.</li>\\r\\n<li>Usual booking termsconditions_creditcard and conditions apply and all bookings are subject to availability.</li>\\r\\n<li>AAE Travel Pte Ltd reserves the right to vary the voucher conditions of use or to withdraw the voucher at any time. AAE Travel Pte Ltd&rsquo;s decision is final in all matters relating to this promotion.</li>\\r\\n<li>AAE Travel Pte Ltd is the promoter of this offer.</li>\\r\\n<li>The voucher is an offer from AAE Travel Pte Ltd and may only be used by residents of Malaysia aged 18 and over.</li>\\r\\n<li>If we become aware, or have reason to suspect (in our reasonable opinion), that you have: (a) made multiple bookings on the Website using the voucher with a view to re-selling any accommodation; or (b) otherwise engaged in conduct which impacts on the fairness, integrity or proper conduct of this offer, we may, in our absolute discretion, cancel all bookings made by you using the voucher.</li>\\r\\n</ol>";
////        h5.replaceAll("\r\n","\n");
//        h5 = voucherModel.getTerms_and_condition();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            // flags
//            // FROM_HTML_MODE_COMPACT：html块元素之间使用一个换行符分隔
//            // FROM_HTML_MODE_LEGACY：html块元素之间使用两个换行符分隔
//            tv_content.setText(Html.fromHtml(h5, Html.FROM_HTML_MODE_COMPACT));
//        } else {
//            tv_content.setText(Html.fromHtml(h5));
//        }
        tv_voucher_title.setText(voucherModel.getVoucher_name());

        addWebView();

        String string = voucherModel.getTerms_and_condition();
        if (!TextUtils.isEmpty(string)) {
            webView.loadData(string, "text/html", "utf-8");
        }
    }

    @Override
    protected void initListener() {
        iv_cancelsure_ok.setOnClickListener(v -> dismiss());
    }


    @Override
    protected int getGravity() {
        return Gravity.CENTER;
    }

    @Override
    protected int getWidthStyle() {
        return getScreenWidth(0.9f);
    }

    @Override
    protected int getHeightStyle() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }


    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    private void addWebView() {

        //使用new方式这是为了解决当(settings.setJavaScriptEnabled(true))之后会出现TextToSpeech的内存泄漏
        webView = new WebView(getContext());

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(layoutParams);

        webviewLayout.addView(webView);

        setting();

        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    protected void setting() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(false);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        settings.setAllowContentAccess(true);
        settings.setSupportMultipleWindows(true);
        //设置缓存模式
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptCanOpenWindowsAutomatically(false);//设置js可以直接打开窗口，如window.open()，默认为false
        settings.setSupportZoom(false);//是否可以缩放，默认true
        settings.setTextZoom(100);
//        settings.setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
        settings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        settings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        settings.setAppCacheEnabled(false);//是否使用缓存
        settings.setDomStorageEnabled(false);//DOM Storage
        settings.setAllowFileAccess(false); // 允许访问文件
        // displayWebview.getSettings().setUserAgentString("User-Agent:Android");//设置用户代理，一般不用
        settings.setPluginState(WebSettings.PluginState.ON);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        DisplayMetrics dm = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
        settings.setDefaultFontSize(DisplayUtils.dip2px(getContext(), 14)); //可以取1-72之间的任意值，默认16
//        if (dm.densityDpi > 240) {
//        }
//        int screenDensity = getContext().getResources().getDisplayMetrics().densityDpi;
//        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
//        switch (screenDensity) {
//            case DisplayMetrics.DENSITY_LOW:
//                zoomDensity = WebSettings.ZoomDensity.CLOSE;
//                break;
//            case DisplayMetrics.DENSITY_MEDIUM:
//                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
//                break;
//            case DisplayMetrics.DENSITY_HIGH:
//                zoomDensity = WebSettings.ZoomDensity.FAR;
//                break;
//        }
//        settings.setDefaultZoom(zoomDensity);
    }

}
